<template>
  <div ref="chartRef" class="charts-cls"></div>
</template>
<script setup lang="ts" name="Echarts">
import { onMounted, onBeforeUnmount, defineProps, watch, ref } from 'vue'
import * as echarts from 'echarts'
// 获取 dom 和 父组件数据 并定义"myChart"用于初始化图表
let myChart: echarts.ECharts
const props = defineProps({
  options: {
    type: Object,
    default: () => {}
  }
})
const chartRef = ref()
// 绘图表函数
const resizeHandler = () => {
  myChart.resize()
}
// 设置防抖，保证无论拖动窗口大小，只执行一次获取浏览器宽高的方法
const debounce = (fun: { (): void; (): void }, delay: number | undefined) => {
  let timer: number | undefined
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun()
    }, delay)
  }
}
const cancalDebounce = debounce(resizeHandler, 50)
const initCharts = () => {
  myChart = echarts.init(chartRef.value)
  props.options && myChart.setOption(props.options)
}
// 页面成功渲染，开始绘制图表
let chartTimeout: number | undefined = undefined
onMounted(() => {
  chartRef.value && initCharts()
  // 自适应不同屏幕时改变图表尺寸
  window.addEventListener('resize', cancalDebounce)
})
// 页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', cancalDebounce)
  chartTimeout && clearTimeout(chartTimeout)
  myChart?.dispose()
})
// 监听图表数据时候变化，重新渲染图表
watch(
  () => props.options,
  () => {
    if (props.options && myChart) {
      myChart.setOption(props.options, true)
      cancalDebounce()
    }
  },
  { deep: true }
)
</script>
<style lang="less" scoped>
.charts-cls {
  width: 100%;
  height: 100%;
}
</style>
